package com.vaye.im.websocket;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.vaye.common.constant.ImConstant;
import com.vaye.common.utils.UserSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 聊天室(群聊升级版)
 * @author wangzhiyong
 * @date 2023年06月29日 上午20:24
 * 1） value = "/ws/{userId}"
 * onOpen(@PathParam("userId") String userId, Session session){ // ... }
 * 这种方式必须在前端在/后面拼接参数 ws://localhost:7889/productWebSocket/123 ，否则404
 *
 * 2） value = "/ws"
 * onOpen(Session session){ // ... }
 * Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
 * // 获得 ?userId=123 这样的参数
 * @author bart
 */
@Slf4j
@Component
public class PushWebSocket {

    /**
     * 推送消息
     * @author wangzhiyong
     * @date 2023/6/29 上午10:29
     * @param targetUserId 目标人消息ID
     * @param msg 推送的消息
     */
    public void push(Long targetUserId,String msg){
        if (UserSessionUtils.isEmpty()) {
            log.info("没有可推送的用户");
            return;
        }
        if (!ObjectUtils.isEmpty(targetUserId)) {
            try {
                UserSessionUtils.getSession(targetUserId).getBasicRemote().sendText(msg);
            } catch (IOException exception) {
                log.error("系统消息推送失败，targetUserId={},msg={}", targetUserId, msg);
                exception.printStackTrace();
            }
        } else {
            UserSessionUtils.getUserSessions().forEach((k,v) ->{
                try {
                    v.getBasicRemote().sendText(msg);
                } catch (IOException exception) {
                    log.error("系统消息推送失败，targetUserId={},msg={}", targetUserId, msg);
                    exception.printStackTrace();
                }
            });
        }
    }

}
